// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearch;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.NavLogisticsChannel;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.NavLogisticsChannelAddressMapper;
import com.fowo.api.mapper.NavLogisticsChannelIssuMapper;
import com.fowo.api.mapper.NavLogisticsChannelMapper;
import com.fowo.api.mapper.NavLogisticsProviderMapper;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelExcelPo;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelImportPo;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelItemVo;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelItemVoPages;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelSearchParamPo;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelSelectExcelPo;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelSelectParams;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelSelectResult;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelSyncAction;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelVo;
import com.fowo.api.model.nav.logistics.channel.address.NavLogisticsChannelAddressSearchParamPo;
import com.fowo.api.model.nav.logistics.channel.issu.NavLogisticsChannelIssuSearchParamPo;
import com.fowo.api.model.nav.logistics.provider.NavLogisticsProviderItemVo;
import com.fowo.api.model.nav.logistics.provider.NavLogisticsProviderSearchParamPo;
import com.fowo.api.model.nav.logistics.provider.NavLogisticsProviderVo;
import com.fowo.api.service.NavLogisticsChannelAddressService;
import com.fowo.api.service.NavLogisticsChannelIssuService;
import com.fowo.api.service.NavLogisticsChannelService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 物流管理-API对接物流-渠道基本信息 服务实现基类
 * @author 蜂窝蜜造平台 配置人：任凯
 */
@Slf4j
@DataObjectType(NavLogisticsChannel.class)
@DS("ds24")
public class NavLogisticsChannelBaseServiceImpl
  extends ServiceImpl<NavLogisticsChannelMapper, NavLogisticsChannel>
  implements NavLogisticsChannelService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("navLogisticsProviderIdName", "nlp.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;
  /** 选择视图 SQL 视图字段排序对应信息 */
  public static final Map<String, String> SELECT_SORT_MAP = Map.ofEntries();

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected NavLogisticsChannelService self;

  @Resource
  protected NavLogisticsChannelIssuService navLogisticsChannelIssuService;

  @Resource
  protected NavLogisticsChannelAddressService navLogisticsChannelAddressService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected NavLogisticsProviderMapper navLogisticsProviderMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected NavLogisticsChannelSyncAction navLogisticsChannelSyncAction;

  @Resource
  protected Validator validator;

  /**
   * 创建物流管理-API对接物流-渠道基本信息
   * @param model 物流管理-API对接物流-渠道基本信息
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(NavLogisticsChannelVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavLogisticsChannel entity = new NavLogisticsChannel();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    // 物流商 默认值设置
    if (!StringUtils.hasText(model.getProviderName())) {
      model.setProviderName("EBO");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("物流管理-API对接物流-渠道基本信息保存失败");
  }

  /**
   * 更新所有子表
   * @param model 物流管理-API对接物流-渠道基本信息
   */
  protected void updateAllChilds(NavLogisticsChannelVo model) throws Exception {
    if (model.getIssu() != null) {
      navLogisticsChannelIssuService.saveAllByParentNavLogisticsChannel(
        model.getId(),
        model.getIssu()
      );
    }

    if (model.getAddress() != null) {
      navLogisticsChannelAddressService.saveAllByParentNavLogisticsChannel(
        model.getId(),
        model.getAddress()
      );
    }
  }

  /**
   * 返回 物流管理-物流商 下属多级分页 (53029/navLogisticsProviderId)
   */
  @Override
  public Map<String, Page<NavLogisticsChannelItemVoPages>> pagesByNavLogisticsProviderId(
    NavLogisticsChannelSearchParamPo search
  ) {
    search.setDisableDataPremissions(true);
    List<NavLogisticsChannelItemVoPages> listMap =
      baseMapper.selectPagesByNavLogisticsProviderId(search);
    Map<Long, List<NavLogisticsChannelItemVoPages>> pageMap = listMap
      .stream()
      .collect(
        Collectors.groupingBy(
          NavLogisticsChannelItemVoPages::getNavLogisticsProviderId
        )
      );
    Map<String, Page<NavLogisticsChannelItemVoPages>> result = new HashMap<>();
    for (Map.Entry<Long, List<NavLogisticsChannelItemVoPages>> listEntry : pageMap.entrySet()) {
      Page<NavLogisticsChannelItemVoPages> page = new Page<>(
        1,
        search.getPageSize(),
        listEntry.getValue().get(0).getPartRows()
      );
      page.setRecords(listEntry.getValue());
      result.put(listEntry.getKey().toString(), page);
    }
    return result;
  }

  /**
   * 批量更新 物流管理-物流商 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByNavLogisticsProviderLogisticsChannel(
    NavLogisticsProviderVo parentVo,
    List<NavLogisticsChannelItemVo> list
  ) throws Exception {
    for (NavLogisticsChannelItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      NavLogisticsChannel item = new NavLogisticsChannel();
      BeanUtils.copyProperties(itemVo, item);
      item.setNavLogisticsProviderId(parentVo.getId());
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 更新物流管理-API对接物流-渠道基本信息
   * @param model 物流管理-API对接物流-渠道基本信息
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(NavLogisticsChannelVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavLogisticsChannel entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("物流管理-API对接物流-渠道基本信息不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "providerName"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新物流管理-API对接物流-渠道基本信息（带空值）
   * @param model 物流管理-API对接物流-渠道基本信息
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(NavLogisticsChannelVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavLogisticsChannel entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("物流管理-API对接物流-渠道基本信息不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(NavLogisticsChannel::getLastUpdateTime, model.getLastUpdateTime())
      .set(NavLogisticsChannel::getLastUpdateUser, model.getLastUpdateUser())
      .set(
        NavLogisticsChannel::getNavLogisticsProviderId,
        model.getNavLogisticsProviderId()
      )
      .set(NavLogisticsChannel::getExpressId, model.getExpressId())
      .set(NavLogisticsChannel::getExpressName, model.getExpressName())
      .set(NavLogisticsChannel::getRemark, model.getRemark())
      .set(NavLogisticsChannel::getFaceSheet, model.getFaceSheet())
      .set(NavLogisticsChannel::getTrackProvider, model.getTrackProvider())
      .set(
        NavLogisticsChannel::getTrack123SearchProvider,
        model.getTrack123SearchProvider()
      )
      .set(
        NavLogisticsChannel::getTrack123SearchNo,
        model.getTrack123SearchNo()
      )
      .set(
        NavLogisticsChannel::getMaxDeclareAmount,
        model.getMaxDeclareAmount()
      )
      .set(
        NavLogisticsChannel::getReceiptEmailSource,
        model.getReceiptEmailSource()
      )
      .set(NavLogisticsChannel::getReceiptEmail, model.getReceiptEmail())
      .set(NavLogisticsChannel::getStatus, model.getStatus())
      .eq(NavLogisticsChannel::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    NavLogisticsChannelSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 标发设置(issu) 对应的对象
    NavLogisticsChannelIssuSearchParamPo issuSearchParam =
      new NavLogisticsChannelIssuSearchParamPo();
    issuSearchParam.setDisableDataPremissions(true);
    issuSearchParam.setParentNavLogisticsChannelInList(ids);
    NavLogisticsChannelIssuMapper localNavLogisticsChannelIssuMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(NavLogisticsChannelIssuMapper.class);
    issuSearchParam.applySqlSegments();
    List<Long> issuIdList = localNavLogisticsChannelIssuMapper.searchIds(
      issuSearchParam
    );
    if (!issuIdList.isEmpty()) {
      NavLogisticsChannelIssuService localNavLogisticsChannelIssuService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavLogisticsChannelIssuService.class);
      localNavLogisticsChannelIssuService.batchDelete(issuIdList);
    }

    // 处理子表字段 地址设置(address) 对应的对象
    NavLogisticsChannelAddressSearchParamPo addressSearchParam =
      new NavLogisticsChannelAddressSearchParamPo();
    addressSearchParam.setDisableDataPremissions(true);
    addressSearchParam.setParentNavLogisticsChannelInList(ids);
    NavLogisticsChannelAddressMapper localNavLogisticsChannelAddressMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(NavLogisticsChannelAddressMapper.class);
    addressSearchParam.applySqlSegments();
    List<Long> addressIdList = localNavLogisticsChannelAddressMapper.searchIds(
      addressSearchParam
    );
    if (!addressIdList.isEmpty()) {
      NavLogisticsChannelAddressService localNavLogisticsChannelAddressService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavLogisticsChannelAddressService.class);
      localNavLogisticsChannelAddressService.batchDelete(addressIdList);
    }
  }

  /**
   * 删除物流管理-API对接物流-渠道基本信息
   * @param id 物流管理-API对接物流-渠道基本信息的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除物流管理-API对接物流-渠道基本信息
   * @param ids 物流管理-API对接物流-渠道基本信息的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<NavLogisticsChannelImportPo> excelToImportRow(
    NavLogisticsChannelImportPo row,
    Integer rowNumber,
    NavLogisticsChannelVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<NavLogisticsChannelImportPo> ir =
      new ImportRow<NavLogisticsChannelImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<NavLogisticsChannelImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new NavLogisticsChannelVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, NavLogisticsChannelImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getFaceSheet())) {
      List<SysDictAllItem> faceSheetItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "faceSheet",
          n -> sysDictService.getDictItems("SCM00136")
        );
      NavLogisticsChannelVo finalVo = vo;
      faceSheetItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getFaceSheet()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setFaceSheet(i.getItemValue()),
          () ->
            ir.addError(
              "faceSheet",
              String.format(
                "必须为 %s 中之一",
                faceSheetItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getTrackProvider())) {
      List<SysDictAllItem> trackProviderItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "trackProvider",
          n -> sysDictService.getDictItems("SCM00137")
        );
      NavLogisticsChannelVo finalVo = vo;
      trackProviderItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTrackProvider()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTrackProvider(i.getItemValue()),
          () ->
            ir.addError(
              "trackProvider",
              String.format(
                "必须为 %s 中之一",
                trackProviderItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getTrack123SearchProvider())) {
      List<SysDictAllItem> track123SearchProviderItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "track123SearchProvider",
          n -> sysDictService.getDictItems("SCM00138")
        );
      NavLogisticsChannelVo finalVo = vo;
      track123SearchProviderItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTrack123SearchProvider()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTrack123SearchProvider(i.getItemValue()),
          () ->
            ir.addError(
              "track123SearchProvider",
              String.format(
                "必须为 %s 中之一",
                track123SearchProviderItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getTrack123SearchNo())) {
      List<SysDictAllItem> track123SearchNoItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "track123SearchNo",
          n -> sysDictService.getDictItems("SCM00139")
        );
      NavLogisticsChannelVo finalVo = vo;
      track123SearchNoItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTrack123SearchNo()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTrack123SearchNo(i.getItemValue()),
          () ->
            ir.addError(
              "track123SearchNo",
              String.format(
                "必须为 %s 中之一",
                track123SearchNoItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getReceiptEmailSource())) {
      List<SysDictAllItem> receiptEmailSourceItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "receiptEmailSource",
          n -> sysDictService.getDictItems("SCM00140")
        );
      NavLogisticsChannelVo finalVo = vo;
      receiptEmailSourceItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getReceiptEmailSource()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setReceiptEmailSource(i.getItemValue()),
          () ->
            ir.addError(
              "receiptEmailSource",
              String.format(
                "必须为 %s 中之一",
                receiptEmailSourceItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00134")
        );
      NavLogisticsChannelVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    // 处理关联字段“物流商编号”
    if (
      !SheetUtils.isBlank(row.getNavLogisticsProviderIdName()) &&
      SheetUtils.isBlank(row.getNavLogisticsProviderId())
    ) {
      NavLogisticsProviderSearchParamPo navLogisticsProviderIdSearchParam =
        new NavLogisticsProviderSearchParamPo();
      navLogisticsProviderIdSearchParam.setLimit(2); // 最大只返回二行记录
      navLogisticsProviderIdSearchParam.setNameEq(
        SheetUtils.trim(row.getNavLogisticsProviderIdName())
      );
      navLogisticsProviderIdSearchParam.applySqlSegments();
      List<NavLogisticsProviderItemVo> navLogisticsProviderIdMatches =
        navLogisticsProviderMapper.search(navLogisticsProviderIdSearchParam);
      if (navLogisticsProviderIdMatches.size() == 0) {
        ir.addError(
          "navLogisticsProviderIdName",
          "未能在物流商中找到匹配的数据"
        );
      } else if (navLogisticsProviderIdMatches.size() > 1) {
        ir.addError(
          "navLogisticsProviderIdName",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setNavLogisticsProviderId(
          navLogisticsProviderIdMatches.get(0).getId()
        );
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", navLogisticsProviderIdMatches.get(0).getId())
          .put("fromObjectName", "NavLogisticsChannel")
          .put("fromObjectId", vo.getId())
          .put("fromField", "navLogisticsProviderId")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "providerName"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("name")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("providerName")
              .rowFieldName("providerName")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(navLogisticsProviderIdMatches),
          joinModels
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<NavLogisticsChannelImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<NavLogisticsChannelImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            NavLogisticsChannelImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              NavLogisticsChannelImportPo row,
              AnalysisContext cxt
            ) {
              NavLogisticsChannelVo vo = new NavLogisticsChannelVo();
              ImportRow<NavLogisticsChannelImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<NavLogisticsChannelImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<NavLogisticsChannelImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      NavLogisticsChannelVo vo = new NavLogisticsChannelVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    NavLogisticsChannelSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "navLogisticsProviderId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavLogisticsChannelItemVo) r).getNavLogisticsProviderIdName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "faceSheet",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00136")
      );
      exportOptions.addFieldMappingOption(
        "trackProvider",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00137")
      );
      exportOptions.addFieldMappingOption(
        "track123SearchProvider",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00138")
      );
      exportOptions.addFieldMappingOption(
        "track123SearchNo",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00139")
      );
      exportOptions.addFieldMappingOption(
        "receiptEmailSource",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00140")
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00134")
      );
      exportOptions.addStringFields(
        "navLogisticsProviderIdName",
        "providerName",
        "expressId",
        "expressName",
        "remark",
        "faceSheet",
        "trackProvider",
        "track123SearchProvider",
        "track123SearchNo",
        "maxDeclareAmount",
        "receiptEmailSource",
        "receiptEmail",
        "status"
      );

      String fileName = String.format(
        "物流管理-API对接物流-渠道基本信息(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> faceSheetItems = sysDictService.getDictItems(
      "SCM00136"
    );
    List<SysDictAllItem> trackProviderItems = sysDictService.getDictItems(
      "SCM00137"
    );
    List<SysDictAllItem> track123SearchProviderItems =
      sysDictService.getDictItems("SCM00138");
    List<SysDictAllItem> track123SearchNoItems = sysDictService.getDictItems(
      "SCM00139"
    );
    List<SysDictAllItem> receiptEmailSourceItems = sysDictService.getDictItems(
      "SCM00140"
    );
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00134");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<NavLogisticsChannelExcelPo> items =
      new ArrayList<NavLogisticsChannelExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<NavLogisticsChannelItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<NavLogisticsChannelItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (NavLogisticsChannelItemVo item : list) {
        NavLogisticsChannelExcelPo excel = new NavLogisticsChannelExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getFaceSheet() != null) {
          faceSheetItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getFaceSheet()))
            .findFirst()
            .ifPresent(i -> excel.setFaceSheet(i.getItemText()));
        }
        if (item.getTrackProvider() != null) {
          trackProviderItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getTrackProvider()))
            .findFirst()
            .ifPresent(i -> excel.setTrackProvider(i.getItemText()));
        }
        if (item.getTrack123SearchProvider() != null) {
          track123SearchProviderItems
            .stream()
            .filter(i ->
              i.getItemValue().equals(item.getTrack123SearchProvider())
            )
            .findFirst()
            .ifPresent(i -> excel.setTrack123SearchProvider(i.getItemText()));
        }
        if (item.getTrack123SearchNo() != null) {
          track123SearchNoItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getTrack123SearchNo()))
            .findFirst()
            .ifPresent(i -> excel.setTrack123SearchNo(i.getItemText()));
        }
        if (item.getReceiptEmailSource() != null) {
          receiptEmailSourceItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getReceiptEmailSource()))
            .findFirst()
            .ifPresent(i -> excel.setReceiptEmailSource(i.getItemText()));
        }
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "物流管理-API对接物流-渠道基本信息(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(NavLogisticsChannelExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过物流渠道名称查询物流管理-API对接物流-渠道基本信息主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByExpressName(String expressName) {
    return this.baseMapper.getIdByExpressName(expressName);
  }

  /**
   * 通过物流渠道名称查询物流管理-API对接物流-渠道基本信息多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByExpressName(List<String> list) {
    return this.baseMapper.getIdsByExpressName(list);
  }

  /**
   * 通过物流管理-API对接物流-渠道基本信息主键查询物流渠道名称
   */
  @Override
  public String getExpressNameById(Long id) {
    return this.baseMapper.getExpressNameById(id);
  }

  /**
   * 通过物流管理-API对接物流-渠道基本信息主键查询物流渠道名称列表
   */
  @Override
  public List<String> getExpressNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getExpressNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("expressName"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 物流管理-API对接物流-渠道基本信息的主键
   */
  @Override
  public NavLogisticsChannelVo getVoById(Long id) throws Exception {
    NavLogisticsChannelVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    NavLogisticsChannelIssuSearchParamPo issuSearchParamPo =
      new NavLogisticsChannelIssuSearchParamPo();
    issuSearchParamPo.setParentNavLogisticsChannel(id);
    issuSearchParamPo.getExtendData().put("queryMode", "sub");
    issuSearchParamPo.getExtendData().put("queryParent", "NavLogisticsChannel");
    issuSearchParamPo.applySqlSegments();
    vo.setIssu(navLogisticsChannelIssuService.search(issuSearchParamPo));

    NavLogisticsChannelAddressSearchParamPo addressSearchParamPo =
      new NavLogisticsChannelAddressSearchParamPo();
    addressSearchParamPo.setParentNavLogisticsChannel(id);
    addressSearchParamPo.getExtendData().put("queryMode", "sub");
    addressSearchParamPo
      .getExtendData()
      .put("queryParent", "NavLogisticsChannel");
    addressSearchParamPo.applySqlSegments();
    vo.setAddress(
      navLogisticsChannelAddressService.search(addressSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询物流管理-API对接物流-渠道基本信息
   * @param search 查询条件
   * @return 物流管理-API对接物流-渠道基本信息分页查询结果
   */
  @Override
  public Page<NavLogisticsChannelItemVo> pageSearch(
    NavLogisticsChannelSearchParamPo search
  ) {
    Page<NavLogisticsChannelItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(NavLogisticsChannelItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 物流管理-API对接物流-渠道基本信息快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'NavLogisticsChannelOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<NavLogisticsChannelItemVo>> searchOptions(
    NavLogisticsChannelSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询物流管理-API对接物流-渠道基本信息
   * @param search 查询条件
   * @return 物流管理-API对接物流-渠道基本信息列表查询结果
   */
  @Override
  public List<NavLogisticsChannelItemVo> search(
    NavLogisticsChannelSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询物流管理-API对接物流-渠道基本信息最后更新时间
   * @param search 查询条件
   * @return 物流管理-API对接物流-渠道基本信息最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(NavLogisticsChannelSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 同步
   */
  @Override
  public void sync(Long id) throws Exception {
    if (navLogisticsChannelSyncAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navLogisticsChannelSyncAction.run(id);
  }

  /**
   * 选择视图分页
   */
  @Override
  public Page<NavLogisticsChannelSelectResult> selectPage(
    NavLogisticsChannelSelectParams params
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      params.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return this.baseMapper.selectPage(params.toPage(), params);
  }

  /**
   * 选择视图导出
   */
  /**
   * 选择视图导出是否需要后台执行
   */
  @Override
  public Boolean SelectBackgroundExportFlag(
    NavLogisticsChannelSelectParams params
  ) throws Exception {
    return baseMapper.SelectTotal(params) > ExcelConfig.THRESHOLD;
  }

  @Override
  public void SelectExport(
    Long templateId,
    NavLogisticsChannelSelectParams params,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      throw new RException("暂不支持模版！");
    }

    int current = 1;
    List<NavLogisticsChannelSelectExcelPo> items = new ArrayList<>();
    while (true) {
      params.setCurrent(current);
      params.setPageSize(EXPORT_QUERY_MAX_SIZE);
      Page<NavLogisticsChannelSelectResult> page = selectPage(params);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<NavLogisticsChannelSelectResult> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (NavLogisticsChannelSelectResult item : list) {
        NavLogisticsChannelSelectExcelPo excel =
          new NavLogisticsChannelSelectExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }
    String fileName = String.format(
      "物流管理-API对接物流-渠道基本信息(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(NavLogisticsChannelSelectExcelPo.class)
      .doWrite(items);
  }
}
